package com.example.dictionary.repository;

import com.example.memento.model.DictionarySource;
import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

import static com.example.memento.model.table.DictionarySourceTableDef.DICTIONARY_SOURCE;

/**
 * 词典源配置Mapper
 * 使用MyBatis-Flex进行数据访问
 */
@Mapper
public interface DictionarySourceMapper extends BaseMapper<DictionarySource> {
    
    /**
     * 根据名称查找词典源
     */
    @Select("SELECT * FROM dictionary_sources WHERE name = #{name}")
    DictionarySource findByName(@Param("name") String name);
    
    /**
     * 查找所有启用的词典源
     */
    default List<DictionarySource> findEnabledSources() {
        return selectListByQuery(QueryWrapper.create()
                .where(DICTIONARY_SOURCE.ENABLED.eq(true))
                .orderBy(DICTIONARY_SOURCE.CREATED_AT.desc()));
    }
    
    /**
     * 查找所有禁用的词典源
     */
    default List<DictionarySource> findDisabledSources() {
        return selectListByQuery(QueryWrapper.create()
                .where(DICTIONARY_SOURCE.ENABLED.eq(false))
                .orderBy(DICTIONARY_SOURCE.CREATED_AT.desc()));
    }
    
    /**
     * 根据格式查找词典源
     */
    default List<DictionarySource> findByFormat(String format) {
        return selectListByQuery(QueryWrapper.create()
                .where(DICTIONARY_SOURCE.FORMAT.eq(format))
                .orderBy(DICTIONARY_SOURCE.CREATED_AT.desc()));
    }
    
    /**
     * 更新启用状态
     */
    @Select("UPDATE dictionary_sources SET enabled = #{enabled}, updated_at = CURRENT_TIMESTAMP WHERE name = #{name}")
    int updateEnabledStatus(@Param("name") String name, @Param("enabled") boolean enabled);
    
    /**
     * 更新最后下载时间
     */
    @Select("UPDATE dictionary_sources SET last_downloaded_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE name = #{name}")
    int updateLastDownloadedTime(@Param("name") String name);
    
    /**
     * 统计词典源数量
     */
    @Select("SELECT COUNT(*) FROM dictionary_sources")
    long countAll();
    
    /**
     * 统计启用的词典源数量
     */
    @Select("SELECT COUNT(*) FROM dictionary_sources WHERE enabled = true")
    long countEnabled();
    
    /**
     * 按格式统计
     */
    @Select("SELECT format, COUNT(*) as count FROM dictionary_sources WHERE format IS NOT NULL GROUP BY format")
    List<Object> countByFormat();
}
